package vip.yuange.gsyzm.utils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
      
    public static String sendPost(String url, File file, Map<String, String> formParams, Map<String, String> headerMap) throws IOException {    
        String content = "";    
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {    
            HttpPost httpPost = new HttpPost(url);    
            RequestConfig requestConfig = RequestConfig.custom()    
                    .setConnectTimeout(3000)    
                    .setConnectionRequestTimeout(3000)    
                    .setSocketTimeout(6000)    
                    .build();    
            httpPost.setConfig(requestConfig);    
            if (headerMap != null && !headerMap.isEmpty()) {    
                headerMap.forEach((key, value) -> {    
                    httpPost.addHeader(key, value);    
                });    
            }    
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();    
            builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());   
            if (formParams != null && !formParams.isEmpty()) {    
                for (Map.Entry<String, String> entry : formParams.entrySet()) {    
                    ContentType textPlainContentType = ContentType.create("text/plain", "UTF-8");  
                    builder.addTextBody(entry.getKey(), entry.getValue(), textPlainContentType);    
                }    
            }    
            HttpEntity multipart = builder.build();    
            httpPost.setEntity(multipart);   
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {    
                HttpEntity entity = httpResponse.getEntity();    
                if (entity != null) {    
                    content = EntityUtils.toString(entity, "UTF-8");  
                }    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
        return content;    
    }
    
}
